package com.google.gwt.user.client.rpc.core.java.sql;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;

import java.sql.Timestamp;
import java.util.Date;

/**
 * Custom field serializer for {@link java.sql.Timestamp}.
 */
public final class Timestamp_CustomFieldSerializer {

  public static void deserialize(SerializationStreamReader streamReader,
      Timestamp instance) throws SerializationException {
    instance.setNanos(streamReader.readInt());
  }

  public static Timestamp instantiate(SerializationStreamReader streamReader)
      throws SerializationException {
	  Timestamp ts= new Timestamp(streamReader.readLong());
	  
	  if (GWT.isClient()) {
		  ts.applyTimeZone();
	  }
	  
    return ts;
  }

  public static void serialize(SerializationStreamWriter streamWriter,
      Timestamp instance) throws SerializationException {
	  
	   long t = instance.getTime();
	   if (GWT.isClient()) {
		   t = t + instance.getServerConversionOffset()*60*1000  ; 
	   }
	   

	streamWriter.writeLong(t);	  
	
	//we can remove the nano sec
    streamWriter.writeInt(instance.getNanos());
  }
}
